﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

namespace PizzaWic.admin
{
    /// <summary>
    /// permet de gerer les produits (edition, suppression)
    /// </summary>
    public partial class ProductManagement : System.Web.UI.Page
    {
        public static List<int> rawMaterialListAdd = new List<int>();
        private DataSet lastDataSet;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //chargement des données
                SqlAccess sql = new SqlAccess();
                DataSet dataSetProduct = new DataSet();
                dataSetProduct = sql.getAllProducts();
                this.MonRepeater.ItemDataBound += new RepeaterItemEventHandler(MonRepeater_ItemDataBound);
                MonRepeater.DataSource = dataSetProduct;
                MonRepeater.DataBind();
            }
        }

        //action sur le repeater
        protected void MonRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            SqlAccess sql = new SqlAccess();
            //edition d'un produit
            if (e.CommandName == "edit_product")
            {
                //mise à jour des nouvelle valeurs
                Object[] data = new Object[5];
                data[0] = e.CommandArgument;
                data[1] = ((TextBox)e.Item.FindControl("editName")).Text;
                data[2] = ((DropDownList)e.Item.FindControl("editType")).SelectedValue.ToString();
                data[3] = ((TextBox)e.Item.FindControl("editPrice")).Text;
                FileUpload fileUploader = (FileUpload)e.Item.FindControl("FileUpload1");
                //telechargement du fichier
                if (fileUploader.HasFile)
                {
                    if (File.Exists(Server.MapPath("../images/imageUser/") + Path.GetFileName(fileUploader.FileName)))
                    {
                        File.Delete(Server.MapPath("../images/imageUser/") + Path.GetFileName(fileUploader.FileName));
                    }
                    fileUploader.SaveAs(Server.MapPath("../images/imageUser/") + Path.GetFileName(fileUploader.FileName));
                    data[4] = "imageUser/" + Path.GetFileName(fileUploader.FileName);
                }
                else
                {
                    data[4] = ((HiddenField)e.Item.FindControl("HF_file")).Value;
                }

                //mise à jour en base
                sql.setProduct(data);
                rawMaterialListAdd.Clear();

                //mise à jour des raw_material lié à ce produit
                Repeater Repeater1 = (Repeater)e.Item.FindControl("Repeater1");

                for (int count = 0; count < Repeater1.Items.Count; count++)
                {
                    HiddenField hf = (HiddenField)Repeater1.Items[count].FindControl("HF_rawMaterial");
                    CheckBox chk = (CheckBox)Repeater1.Items[count].FindControl("rawMaterialId");
                    if (chk.Checked)
                    {
                        rawMaterialListAdd.Add((int.Parse(hf.Value)));
                    }
                }

                //suppression de tout les rawmaterial du produit
                sql.delProductRawMaterial(e.CommandArgument);
                //ajout des nouveau raw_material pour ce produit
                foreach (int i in rawMaterialListAdd)
                {
                    data = new Object[2];
                    data[0] = e.CommandArgument;
                    data[1] = i;
                    sql.addProductRawMaterial(data);
                }
            }

            //suppression d'un produit
            else if (e.CommandName == "delete_product")
            {
                Object[] param = new Object[1];
                param[0] = e.CommandArgument;
                sql.delProduct(param);
            }

            //mise à jour de la vue
            DataSet dataSetProduct = new DataSet();
            dataSetProduct = sql.getAllProducts();
            this.MonRepeater.ItemDataBound += new RepeaterItemEventHandler(MonRepeater_ItemDataBound);
            MonRepeater.DataSource = dataSetProduct;
            MonRepeater.DataBind();
        }

        //au chargement des item du repeater
        private void MonRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType !=
                    ListItemType.AlternatingItem)
                return;

            DropDownList ddList = (DropDownList)e.Item.FindControl("editType");
            ddList.SelectedValue = ((Label)e.Item.FindControl("LabelType")).Text;

            HiddenField hf = (HiddenField)e.Item.FindControl("HiddenFieldrm");
            int id = int.Parse(hf.Value);

            Repeater subrepeater1 = (e.Item.FindControl("Repeater1") as Repeater);
            Repeater subrepeater = (e.Item.FindControl("Repeater2") as Repeater);

            //permet d'obtenir la liste des raw_material pour ce produit
            SqlAccess sql = new SqlAccess();
            DataSet dataGetRawMaterial = new DataSet();
            Object[] param = new Object[1];
            param[0] = id;
            dataGetRawMaterial = sql.getRawMaterialByProduct(param);

            //sauvegarde pour les checkbox lors de l'edition
            lastDataSet = dataGetRawMaterial;

            //mise à jour de la vue des raw_material
            subrepeater.DataSource = dataGetRawMaterial;
            subrepeater.DataBind();

            dataGetRawMaterial = sql.getAllRawMaterial();
            subrepeater1.DataSource = dataGetRawMaterial;
            subrepeater1.DataBind();
        }


        //permet de checker la checkbox si le raw_material correspondant est utliser pour ce produit
        public void checkBoxChecked(Object Sender, RepeaterItemEventArgs e)
        {
            CheckBox cb = (CheckBox)e.Item.FindControl("rawMaterialId");

            HiddenField hf = (HiddenField)e.Item.FindControl("HF_rawMaterial");
            int rrr = lastDataSet.Tables[0].Rows.Count;
            for (int i = 0; i < lastDataSet.Tables[0].Rows.Count; i++)
                if (int.Parse(hf.Value) == (int)lastDataSet.Tables[0].Rows[i][0])
                {
                    cb.Checked = true;
                }
        }

        //permet d'actuliser la liste des ingredients lors d'une action sur une checkbox
        protected void addRawMaterialToProduct(Object sender, EventArgs args)
        {
            CheckBox box = sender as CheckBox;

            RepeaterItem item = box.NamingContainer as RepeaterItem;
            HiddenField hf = item.FindControl("HiddenFieldrm") as HiddenField;
            int id = int.Parse(hf.Value);
            if (box.Checked)
                rawMaterialListAdd.Add(id);
            else
                rawMaterialListAdd.Remove(id);
        }
    }
}
